import datetime
import logging
import os
import sys
from datetime import timedelta

import eventlet
from eventlet import wsgi
from flask import Flask, render_template, redirect
from flask_socketio import SocketIO
# from flask_cors import CORS

from views.admin import admin_blueprint
from views.user import user_blueprint
from websocket.chat_room import init_user_chat

IP = '0.0.0.0'
PORT = 80

eventlet.monkey_patch()


def creat_app():
    app_ = Flask(__name__)

    app_.register_blueprint(admin_blueprint)
    app_.register_blueprint(user_blueprint)

    @app_.errorhandler(404)
    def error_date(error):
        return render_template("./error/404.html"), 404

    @app_.errorhandler(500)
    def error_date(error):
        return render_template("./error/500.html"), 500

    @app_.route('/')
    def index_():
        return redirect("/user/home")

    # 配置session
    app_.config['SECRET_KEY'] = os.urandom(24)
    app_.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 配置7天有效

    return app_


def init_logger():
    console_level = logging.INFO
    file_level = logging.INFO
    file_handler = logging.FileHandler(f'./log/{datetime.datetime.now().strftime("%Y-%m-%d-%H.%M.%S")}.txt',
                                       mode='a', encoding="utf8")
    file_handler.setFormatter(
        logging.Formatter('%(asctime)s [%(levelname)s] %(module)s.%(lineno)d %(name)s:%(message)s'))
    file_handler.setLevel(file_level)
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(
        logging.Formatter('[%(asctime)s %(levelname)s] %(message)s', datefmt="%Y/%m/%d %H:%M:%S"))
    console_handler.setLevel(console_level)
    logging.basicConfig(level=min(console_level, file_level),
                        handlers=[file_handler, console_handler], )


app = creat_app()
socket_io = SocketIO(app)
init_user_chat(socket_io)


if __name__ == '__main__':
    init_logger()

    logging.info("开始初始化Flask")

    logging.info(f'Flask已启动，IP:{IP} PORT:{PORT}')

    # 全局跨域
    # CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})

    # server = pywsgi.WSGIServer((IP, PORT), app)
    # server.serve_forever()

    # socket_io.run(app, host=IP, port=PORT, debug=False, log_output=True)
    wsgi.server(eventlet.listen((IP, PORT)), app, debug=False)
